package com.easyweb.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.easyweb.cache.StartUpListener;
import com.easyweb.common.Constants;
import com.easyweb.common.PrintUtils;
import com.easyweb.model.KeyWord;
import com.easyweb.model.ResultMsg;
import com.easyweb.model.Users;
import com.easyweb.service.KeyWordService;

@Controller
@RequestMapping("/keyword")
public class KeyWordController {
	
	@Autowired
	private KeyWordService keyWordService;
	
	@RequestMapping(value="/merge",method=RequestMethod.POST)
	public void add(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE));
			return;
		}
		String description = request.getParameter("description");
		String keyWord = request.getParameter("keyword");
		KeyWord word = keyWordService.getKeyWord();
		KeyWord kw = new KeyWord();
		kw.setDescription(description);
		kw.setKeyword(keyWord);
		int num = 0;
		if(word==null){
			num = keyWordService.insertKeyWord(kw);
		}else{
			num = keyWordService.updateKeyWord(kw);
		}
		if(num > 0){
			StartUpListener.KEYWORD.setDescription(kw.getDescription());
			StartUpListener.KEYWORD.setKeyword(kw.getKeyword());
			PrintUtils.printMsg(response, new ResultMsg());
		}else{
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR,null));
		}
	}
	
	@RequestMapping(value="/get",method=RequestMethod.GET)
	public void get(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE));
			return;
		}
		PrintUtils.printMsg(response, StartUpListener.KEYWORD);
	}
}
